package com.example.springboottest.example.nio.netty.embed;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.embedded.EmbeddedChannel;

/**
 * 将 新 建 三 个 极 为 简 单 的 入 站 处 理 器 ， 在
 * ChannelInitializer 通道初始化处理器的 initChannel 方法中把它们加入到流水线中。三个入站处理器
 * 分别为：SimpleInHandlerA、SimpleInHandlerB、SimpleInHandlerC，添加的顺序为 A → B → C。
 */
public class EmbeddedOutBoundChannelTest {
    public static void main(String[] args) {
        ChannelInitializer i = new ChannelInitializer<EmbeddedChannel>() {
            protected void initChannel(EmbeddedChannel ch) {
                ch.pipeline().addLast(new SimpleOutHandlerA());
                ch.pipeline().addLast(new SimpleOutHandlerB());
                ch.pipeline().addLast(new SimpleOutHandlerC());

                ch.pipeline().addLast(new EmbeddedInBoundChannelTest.SimpleInHandlerA());
                ch.pipeline().addLast(new EmbeddedInBoundChannelTest.SimpleInHandlerB());
                ch.pipeline().addLast(new EmbeddedInBoundChannelTest.SimpleInHandlerC());
            }
        };
        EmbeddedChannel channel = new EmbeddedChannel(i);
        ByteBuf buf = Unpooled.buffer();
        buf.writeInt(1);
        //向通道写一个出站报文(或数据包)
        channel.writeOutbound(buf);
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class SimpleOutHandlerA extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise
                promise) throws Exception {
            ByteBuf buf = ((ByteBuf) msg);
            int num = buf.readInt();
            System.out.println("出站处理器 A: 被回调 ，消息是" + num);
            super.write(ctx, buf.writeInt(--num), promise);
        }
    }

    static class SimpleOutHandlerB extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise
                promise) throws Exception {
            ByteBuf buf = ((ByteBuf) msg);
            int num = buf.readInt();
            System.out.println("出站处理器 B: 被回调 ，消息是" + num);
            super.write(ctx, buf.writeInt(--num), promise);
        }
    }

    static class SimpleOutHandlerC extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise
                promise) throws Exception {
            ByteBuf buf = ((ByteBuf) msg);
            int num = buf.readInt();
            System.out.println("出站处理器 C: 被回调 ，消息是" + num);
            super.write(ctx, buf.writeInt(--num), promise);
        }
    }
}
